/* cl.ext.ext.selectedmove 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery',"jsTree"], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                var reqJsTree = require('jsTree');
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($){
        var defaultJsTree={
            "core": {
                "themes": {"responsive": false},
                "cache": false,
                "data": []
                //"dblclick_toggle":false
            },
            "types": {"default": {"icon": false}},
            "plugins": ["types", "checkbox", "search"]
        };
        var defaults={
            theme:"tree",
            placeholder:"",
            attrName:"",
            isSearchMulti:true,
            splitSearchMulti:",",
            isMergeParent:true,
            checkMaxLength:0,
            initvalue:"",//[{id:1,name:"222"}] || ["1","2"] || "1,2,3"
            initindex:-1,
            data:[],
            ajax:{},//url data
            infoJsTree:defaultJsTree,
            afterAjaxCallback:null,
            initCallback:null
            //changeCallback:null //待需求实现
        };
        var $modalCommon={
            getDefaults :function () {
                return defaults
            },
            getOptions : function (elementData,options) {
                options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                return optionBase
            }
        };
        var modalOperateElement=function(element,options){
            var self=this;
            self.optionModal=options;
            self.elementModal = element;
        };
        modalOperateElement.prototype = {
            init:function(){
                var self=this;
                self.bindEvent();
                switch(self.optionModal.theme){
                    case "tree":
                        self.tree().initTree();
                        break
                }
            },
            bindEvent:function(){
                var self=this;
                self.elementModal.textSearch.off("keydown").on("keydown",function(event){if(event.keyCode == 13) {self.operateSearchValue();}});
                self.elementModal.textSearch.next(".search-icon").off("click").on("click",function(){self.operateSearchValue();});
                self.elementModal.bodySelect.on('click', '.move-selected-remove', function () {
                    var _this=$(this);
                    var interestid=_this.data("interestid");
                    _this.parent().remove();
                    switch(self.optionModal.theme){
                        case "tree":
                            self.tree().removeSelectNode(interestid);
                            break
                    }
                });
            },
            getSelectedId:function(){
               return this.getPanelSelectedData();
            },
            getSelectedList:function(){
                return $.map(this.elementModal.bodySelect.find("li"),function(obj){
                    var _this=$(obj);
                    return {id:_this.data("interestid"),name:obj.textContent}
                });
            },
            setSelected:function(value){
                var self=this;
                switch(self.optionModal.theme){
                    case "tree":
                        self.tree().initTreeSelected(value);
                        break
                }
            },
            clearSelected:function(){
                var self=this;
                self.setPanelSelectedData([]);
                self.computeSelectCount();
                self.elementModal.bodySelect.html("");
                self.elementModal.textSearch.val("");
                switch(self.optionModal.theme){
                    case "tree":
                        self.tree().clearAll();
                        break
                }
            },
            tree:function(){
                var self=this;
                return {
                    initTree:function(){
                        var selfTree=this;
                        var jsonData= $.ExtCommon.isCheckEmpty(self.optionModal.data)?[]:self.optionModal.data;
                        if(selfTree.isInit){
                            selfTree.initTreeSelected(self.optionModal.initvalue)
                        }else{
                            self.optionModal.infoJsTree.core.data=jsonData;
                            self.elementModal.bodyList.jstree(self.optionModal.infoJsTree);
                            setTimeout(function(){
                                selfTree.bindTreeEvent();
                                selfTree.isInit=true;
                                selfTree.initTreeSelected(self.optionModal.initvalue)
                            },200);
                        }
                    },
                    bindTreeEvent:function(){
                        var selfTree=this;
                        self.elementModal.bodyList.on("changed.jstree", function (e, data) {
                            if(data.node) {
                                var info= data.node;
                                var arrAddId=[];
                                var arrDeleteId=[];
                                if (data.action == "deselect_node") {
                                    arrDeleteId.push(info.id);
                                    if(info.children_d.length>0){arrDeleteId=arrDeleteId.concat(info.children_d);}
                                    if(self.optionModal.isMergeParent){
                                        if(info.parents.length>0){
                                            $.each(info.parents,function(i,pid){
                                                if(pid!="#"){
                                                    var treeParent=selfTree.getTreeNode(pid);
                                                    var treeChildrenSelected=$.map(treeParent.children,function(cid){
                                                        var treeChildren=selfTree.getTreeNode(cid);
                                                        if(treeChildren.state.selected){
                                                            return treeChildren;
                                                        }
                                                    });
                                                    if(treeChildrenSelected.length+1==treeParent.children.length){
                                                        arrDeleteId.push(pid);
                                                        arrAddId=arrAddId.concat($.map(treeChildrenSelected,function(info){return info.original}));
                                                        if(treeParent.parent=="#"){return false;}
                                                    }else{
                                                        return false;
                                                    }
                                                }
                                            });
                                        }
                                    }
                                }
                                else if (data.action == "select_node") {
                                    if(self.optionModal.isMergeParent){
                                        if(info.children_d.length>0){arrDeleteId=arrDeleteId.concat(info.children_d);}
                                        if(info.parents.length>0){
                                            $.each(info.parents,function(i,pid){
                                                if(pid!="#"){
                                                    var treeParent=selfTree.getTreeNode(pid);
                                                    if(treeParent.state.selected){
                                                        arrAddId.push(treeParent.original);
                                                        arrDeleteId=arrDeleteId.concat(treeParent.children);
                                                        if(treeParent.parent=="#"){return false;}
                                                    }else{
                                                        if(i==0){arrAddId.push(info.original);}
                                                        return false;
                                                    }
                                                }else{
                                                    arrAddId.push(info.original);
                                                }
                                            });
                                        }
                                    }else{
                                        if(info.children_d.length>0){
                                            var onlyChildren=info.children_d.length==info.children.length
                                                ? info.children_d
                                                :$.map(info.children_d,function(cid){if(info.children.indexOf(cid)==-1){return cid}});
                                            $.each(onlyChildren,function(i,cid){
                                                var treeChildren=selfTree.getTreeNode(cid);
                                                if(treeChildren.state.selected && treeChildren.children.length==0){
                                                    arrAddId.push(treeChildren.original);
                                                }
                                            });
                                        }else{
                                            arrAddId.push(info.original);
                                        }
                                    }
                                }
                                if(arrAddId.length>0 || arrDeleteId.length>0){ self.editPanelSelected(arrDeleteId,arrAddId);}
                            }
                        });
                    },
                    initTreeSelected:function(selectedValue){
                        var selfTree=this;
                        var isEmpty= $.ExtCommon.isCheckEmpty(selectedValue);
                        if(!isEmpty){
                            selfTree.setSelectNode(selectedValue);
                        }else{
                            self.setPanelSelectedData([]);
                            self.computeSelectCount();
                        }
                        setTimeout(function(){self.scrollTopMoveBody(isEmpty?"":".jstree-clicked");},200);
                    },
                    getTree:function(){
                        return self.elementModal.bodyList.jstree();
                    },
                    getTreeNode:function(id){
                        return this.getTree().get_node(id);
                    },
                    setSelectNode:function(selectedValue){
                        var arrIds=$.type(selectedValue)=="string"
                            ?selectedValue.split(",")
                            :$.map(selectedValue,function(info){return $.type(info)=="object"?info.id:info;});
                        this.getTree().select_node(arrIds); //true
                    },
                    removeSelectNode:function(id){
                        this.getTree().deselect_node(id);
                    },
                    setSearch:function(searchKey,isSearchMulti,strSplit){
                        var selfTree=this;
                        isSearchMulti= $.ExtCommon.isCheckEmpty(isSearchMulti)?false:isSearchMulti;
                        strSplit=$.ExtCommon.isCheckEmpty(strSplit)?",":strSplit;
                        if(isSearchMulti){
                            var arrSearch=searchKey.replace(/，/g, ',').split(strSplit);
                            $.each(arrSearch,function(i,info){
                                selfTree.getTree().search(info,undefined,undefined,undefined,true);
                            });
                        }else{
                            selfTree.getTree().search(searchKey);
                        }
                    },
                    clearSearch:function(){
                        this.getTree().clear_search();
                    },
                    clearAll:function(){
                        this.getTree().deselect_all(true);
                        this.getTree().close_all();
                        this.clearSearch();
                        this.getTree().refresh();
                    }
                };
            },
            getPanelSelectedData:function(){
                var dataSelect = this.elementModal.bodySelect.data("selectedId");
                return dataSelect||[];
            },
            setPanelSelectedData:function(json){
                this.elementModal.bodySelect.data("selectedId",json);
            },
            editPanelSelected:function(remove,add){
                var self=this;
                if(!$.ExtCommon.isCheckEmpty(remove)){
                    remove= $.ExtCommon.getArrUnique(remove);
                    this.removePanelSelected(self.optionModal.attrName,remove);
                }
                if(!$.ExtCommon.isCheckEmpty(add)){
                    add= $.map(add,function(info){if(remove.indexOf(info.id.toString())==-1){return info;}});
                    this.createPanelSelected(self.optionModal.attrName,add);
                }
                self.computeSelectCount();
            },
            removePanelSelected:function(type,ids){
                var self=this;
                var tempRemoveIds=[];
                $.isArray(tempRemoveIds)?tempRemoveIds=ids:tempRemoveIds.push(ids);
                if(tempRemoveIds.length>0){
                    var dataSelect = self.getPanelSelectedData();
                    var arrIds=[];
                    $.each(tempRemoveIds,function(i,info){
                        var id=info.toString();
                        var tempIndex=dataSelect.indexOf(id);
                        if(tempIndex>-1){
                            dataSelect.splice(tempIndex,1);
                            arrIds.push("#"+self.getPanelSelectedId(type,id));
                        }
                    });
                    if(arrIds.length>0){$(arrIds.join(",")).empty().remove();}
                    self.setPanelSelectedData(dataSelect);
                }
            },
            createPanelSelected:function(type,json) {
                var self = this;
                var tempCreateList = [];
                if($.isArray(json)){
                    tempCreateList = json
                }else{
                    tempCreateList.push(json);
                }
                if(tempCreateList.length>0) {
                    var dataSelect = self.getPanelSelectedData();
                    var arrHtml = [];
                    $.each(tempCreateList, function (i, info) {
                        var id=info.id.toString();
                        if (dataSelect.indexOf(id) == -1) {
                            dataSelect.push(id);
                            arrHtml.push('<li id="' + self.getPanelSelectedId(type, id) + '" data-interestid="' + id + '"><span>' + info.originalname + '</span><i class="fa fa-close pull-right move-selected-remove" data-interestid="' + id + '"></i></li>');
                        }
                    });
                    if (arrHtml.length > 0) {
                        self.setPanelSelectedData(dataSelect);
                        self.elementModal.bodySelect.append(arrHtml.join(""));
                    }
                }
            },
            computeSelectCount:function(){
                var dataSelect = this.getPanelSelectedData();
                var selectLength=dataSelect.length;
                var maxLength=this.optionModal.checkMaxLength;
                this.elementModal.panelSelectCount.text(selectLength);
                if(maxLength>0){
                    var maxTip=selectLength>maxLength
                        ? $.ExtCommon.getStringConnect("当前已超过 {0} 个",[selectLength-maxLength])
                        :$.ExtCommon.getStringConnect("还剩 {0} 个可选",[maxLength-selectLength]);
                    var maxHtml=$.ExtCommon.getStringConnect("，最多可选择 {0} 个，{1}",[maxLength,maxTip]);
                    this.elementModal.panelSelectMax.html(maxHtml);
                }
            },
            getPanelSelectedId:function(type,id){
                return "li_move_selected_"+type+"_" + id;
            },
            operateSearchValue:function(){
                var self=this;
                var searchKey = $.trim(self.elementModal.textSearch.val());
                switch(self.optionModal.theme){
                    case "tree":
                        self.tree().clearSearch();
                        if(searchKey.length>0) {self.tree().setSearch(searchKey,self.optionModal.isSearchMulti,self.optionModal.splitSearchMulti);}
                        self.scrollTopMoveBody(searchKey.length>0?".jstree-search":"");
                        break
                }
            },
            scrollTopMoveBody:function(elementClass){
                var self=this;
                var elementMoveBody=self.elementModal.bodyList.parent();
                if($.ExtCommon.isCheckEmpty(elementClass)){
                    elementMoveBody.scrollTop(0);
                }else{
                    var elementSearch=this.elementModal.bodyList.find(elementClass);
                    if(elementSearch.length>0){
                        var objP= elementSearch.eq(0);
                        var positionTop=objP.position().top;
                        var scrollTop=elementMoveBody.scrollTop();
                        var distance=50;
                        elementMoveBody.scrollTop(scrollTop>0?scrollTop+(positionTop-distance):positionTop-distance)
                    }else{
                        elementMoveBody.scrollTop(0);
                    }
                }
            }
        };
        var SelectedMoveExtModal = function(element, options) {
            var self=this;
            self.element = $(element);
            self.optionBase=$modalCommon.getOptions(self.element.data(),options);
            var $templateHtml = $('' +
                '<div class="row">'+
                    '<div class="col-xs-6">'+
                        '<div class="search-base" style=""><input type="text" class="form-control search-text" placeholder="'+self.optionBase.placeholder+' 逗号分隔可搜索多个" /><i class="fa fa-search search-icon"></i></div>'+
                        '<div class="move-body-left"><div class="move-body-list"></div></div>'+
                    '</div>'+
                    '<div class="col-xs-6">'+
                        '<div class="selected-title"><span>已选择 <span class="selected-count">0</span> </span>个<span class="selected-max"></span></div>'+
                        '<div class="move-body-right"><ul class="move-body-select"></ul></div>'+
                    '</div>'+
                '</div>');
            self.elementContainer={
                bodyList:$templateHtml.find('.move-body-list'),
                bodySelect:$templateHtml.find('.move-body-select'),
                textSearch:$templateHtml.find('.search-text'),
                panelSelectCount:$templateHtml.find('.selected-count'),
                panelSelectMax:$templateHtml.find('.selected-max')
            };
            self.element.addClass("move-select").append($templateHtml);
            if($.ExtCommon.isCheckEmpty(self.optionBase.ajax.url)){
                self.optionBase.dataOriginalAjax=self.optionBase.data;
                self.init();
            }else{
                var url=self.optionBase.ajax.url;
                var para=self.optionBase.ajax.data;
                para= $.ExtCommon.isCheckEmpty(para)?{}:para;
                $.ExtAjax.initGet({url:url,data:para,
                    successCallback:function(res){
                        var list=res.success? res.data:[];
                        if(!res.success){ $.ExtNotify.error(res.msg);}
                        self.optionBase.dataOriginalAjax=list;
                        if(self.optionBase.afterAjaxCallback){
                            var templist=self.optionBase.afterAjaxCallback(list);
                            self.optionBase.data= $.ExtCommon.isCheckEmpty(templist)?[]:templist;
                        }else{
                            self.optionBase.data=list;
                        }
                        self.init();
                    }
                });
            }
        };
        SelectedMoveExtModal.prototype = {
            init:function(){
                var self=this;
                self.elementOperate=new modalOperateElement(self.elementContainer,self.optionBase);
                self.elementOperate.init();
                if (self.optionBase.initCallback) {self.optionBase.initCallback(self.optionBase.data)}
            },
            getSelectedId:function(){
                return this.elementOperate.getSelectedId();
            },
            getSelectedList:function(){
                return this.elementOperate.getSelectedList();
            },
            setSelected:function(value){
                return this.elementOperate.setSelected(value);
            },
            clearSelected:function(){
                return this.elementOperate.clearSelected();
            }
        };
        $.fn.ExtSelectedMove = function(options) {
            var dataFun;
            this.each(function() {
                var el = $(this);
                var tempData=el.data('ExtSelectedMove');
                if (tempData) {
                    if (typeof  options == "string") {
                        if (tempData[options]) {
                            dataFun =tempData[options]()
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = tempData
                    }
                } else {
                    dataFun = new SelectedMoveExtModal(el, options);
                    el.data('ExtSelectedMove', dataFun);
                }
            });
            return dataFun;
        };
        return SelectedMoveExtModal;
    })
);
